<template>
  <div ref="chart" class="chart-canvas"></div>
</template>

<script>
import { mapState } from "vuex";
import { init, dispose } from "klinecharts";
export default {
  computed: {
    ...mapState({
      lang: (state) => state.system.lang,
    }),
  },
  watch: {
    kLineData: {
      handler(value) {
        if (this.chart) {
          this.setChart(value);
        } else {
          this.$nextTick(() => {
            this.initChart(value);
          });
        }
      },
      immediate: true,
      deep: true,
    },
  },
  props: {
    kLineData: {
      type: Array,
      default() {
        return [];
      },
      required: false,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    // 初始化图表
    this.chart = init(this.$refs.chart);
    if (this.lang == "zh") {
      this.chart.setLocale("zh-CN");
    }
    this.chart.setStyles({
      candle: {
        // 蜡烛柱
        bar: {
          upColor: "#5EC6A3",
          downColor: "#2FC25B",
          noChangeColor: "#888888",
          upBorderColor: "#5EC6A3",
          downBorderColor: "#2FC25B",
          noChangeBorderColor: "#888888",
          upWickColor: "#5EC6A3",
          downWickColor: "#2FC25B",
          noChangeWickColor: "#888888",
        },
        priceMark: {
          show: false,
        },
        tooltip: {
          showRule: "follow_cross",
          showType: "rect",
        },
      },
    });
  },
  unmounted() {
    // 销毁图表
    dispose("chart");
  },
  methods: {
    initChart(data) {
      // 为图表添加数据
      this.chart.applyNewData(data);
    },
    setChart(data) {
      this.chart.applyNewData(data);
    },
  },
};
</script>

<style lang="scss" scoped>
.chart-canvas {
  width: 100%;
  height: 700px;
}
</style>
